#include "socket_lib.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define SERVER_IP "127.0.0.1"
#define PORT 8888
#define MAX_CONNECTION 10

// 模拟业务逻辑处理
void process_request(const char *request, char *response) {
    LOG_INFO("Processing request: %s\n", request);      // 打印接收到的客户端消息
    strcpy(response, "Server response: Received '");    // 回显接收到的消息给客户端
    strcat(response, request);
    strcat(response, "'");
}

// 服务器示例
void server_test() {
    SocketServer server;

    // 初始化服务器
    socket_server_init(&server, SERVER_IP, PORT, MAX_CONNECTION, SELECT_TCP);
    
    // 启动服务器并传入自定义的客户端处理函数
    socket_server_start(&server, &process_request);

    // 停止服务器
    socket_server_stop(&server);
}

// 客户端示例
void client_test() {
    SocketClient client;
    char *response = NULL;

    // 初始化客户端
    socket_client_init(&client, SERVER_IP, PORT);
    
    // 连接到服务器
    socket_client_connect(&client);
  
    // 向服务器发送消息
    socket_client_send(&client, "Hello, Server!", &response);
    
    if (response == NULL) {
        LOG_INFO("Response is NULL\n");
    } else {
        LOG_INFO("Response: %s\n", response);
        free(response); // 确保释放动态分配的内存
    }
    
    // 关闭客户端
    socket_client_close(&client);
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        LOG_INFO("Usage: %s [server|client]\n", argv[0]);
        return 1;
    }

    if (strcmp(argv[1], "server") == 0) {
        LOG_INFO("Starting server...\n");
        server_test();
    } else if (strcmp(argv[1], "client") == 0) {
        LOG_INFO("Starting client...\n");
        client_test();
    } else {
        LOG_INFO("Invalid argument. Use 'server' or 'client'.\n");
        return 1;
    }

    return 0;
}
